#!/bin/bash 

function run_task(){ 
	proc_sql='SELECT call_proc FROM dps.t_report_etl_task WHERE run_date='"'${CURR_DATE}' AND IFNULL(attribute_id,'X')<>'F' ORDER BY run_seq LIMIT ${TASK_SEQ},1"
    
  while read proc
    do
			#echo "TaskNum: $TASK_SEQ, PROC: $proc Running..."
			mysql -u${V_MYSQL_USER} -p${V_MYSQL_PSWD} dps -e "$proc" 2>/dev/null
    done< <(mysql -u${V_MYSQL_USER} -p${V_MYSQL_PSWD} -N -s -e "${proc_sql}" 2>/dev/null)
    
    sleep 1; 
}

V_HOME=/home/hadoop/dev
V_SHELL_SECU=${V_HOME}/scu
V_MYSQL_USER="${V_SHELL_SECU}/mysql_query_user"
V_MYSQL_PSWD="${V_SHELL_SECU}/mysql_query_pswd"
V_MYSQL_USER=$(base64 -di ${V_MYSQL_USER})
V_MYSQL_PSWD=$(base64 -di ${V_MYSQL_PSWD})
SUB_PROCESS_NUM=20
CURR_DATE=$(date +%Y-%m-%d)
CURR_DAY=$(date +%d)
TASK_SEQ=0

TASK_COUNT='SELECT count(*) FROM dps.t_report_etl_task WHERE run_date='"'${CURR_DATE}' AND IFNULL(attribute_id,'X')<>'F'"
while read tasknum
do
  TASK_NUM=$tasknum
done< <(mysql -u${V_MYSQL_USER} -p${V_MYSQL_PSWD} -N -s -e "${TASK_COUNT}" 2>/dev/null)

if [ $TASK_NUM -eq 0 ];then
	#echo "No Procedure Task."
	exit 0
fi

tmpfile="/tmp/$$.fifo"
mkfifo $tmpfile

exec 6<>$tmpfile 
rm -f $tmpfile

for((i=1;i<=$SUB_PROCESS_NUM;i++));
	do 
    echo "init sub job $i.";
	done >&6

for ((i=i;i<=$TASK_NUM;i++)); 
	do
    read line 
    echo "$line"
    TASK_SEQ=$[ $i-1 ]
    {
			run_task && {
				echo "a sub is $i finished."
			} || {
				echo "$i sub error"
			}
			echo >&6 
		} &
	done <&6

wait

if [ $CURR_DAY="16" ];then
	proc_f_sql='SELECT call_proc FROM dps.t_report_etl_task WHERE run_date='"'${CURR_DATE}' AND attribute_id='F' ORDER BY run_seq"

	while read proc
	do
		#echo "Run $proc"
		mysql -u${V_MYSQL_USER} -p${V_MYSQL_PSWD} dps -e "$proc" 2>/dev/null
  done< <(mysql -u${V_MYSQL_USER} -p${V_MYSQL_PSWD} -N -s -e "${proc_f_sql}" 2>/dev/null)
fi

# 关闭df6
exec 6>&-

# 成功退出
exit 0
